package com.kevin.utilits.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;

public class DeadLockTest {
	private static String lock1 = "lock1";
	private static String lock2 = "lock2";
	private static Logger logger = Logger.getLogger(DeadLockTest.class);

	public static void main(String[] args) {
		ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
		for (int i = 0; i < 1; i++) {
			fixedThreadPool.submit(new Runnable() {
				public void run() {
					while (true) {
						try {
							synchronized (lock1) {
								Thread.sleep(RandomUtils.nextInt(100));
							}
							synchronized (lock2) {
								Thread.sleep(RandomUtils.nextInt(100));
							}
						} catch (InterruptedException e) {
							logger.error(e.getMessage(), e);
						}
					}
				}
			});
		}
		for (int i = 0; i < 1; i++) {
			fixedThreadPool.submit(new Runnable() {
				public void run() {
					while (true) {
						try {
							synchronized (lock2) {
								Thread.sleep(RandomUtils.nextInt(100));
							}
							synchronized (lock1) {
								Thread.sleep(RandomUtils.nextInt(100));
							}
						} catch (InterruptedException e) {
							logger.error(e.getMessage(), e);
						}
					}
				}
			});
		}
		try {
			Thread.currentThread().wait();
		} catch (InterruptedException e) {
			logger.error(e.getMessage(), e);
		}
	}
}
